<template>
  <XenListPage
    title="入职申请"
    :dataList="onboardingList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    :showAddButton="false"
    searchPlaceholder="点击筛选入职申请信息"
    emptyText="暂无入职申请信息"
    emptyDesc="点击右上角添加入职申请"
    createPagePath="/subpkg-hr-syshronboardingrequestbill/create"
    detailPagePath="/subpkg-hr-syshronboardingrequestbill/details"
    editPagePath="/subpkg-hr-syshronboardingrequestbill/edit"
    permission-module="SysHrOnboardingRequestBill"
    @delete="handleDelete"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #add-icon>
      <uni-icons type="plus" size="18" color="#ffffff"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-delete>
      <uni-icons type="trash" size="16" color="#FF5252"></uni-icons>
    </template>
    <template #action-icon-edit>
      <uni-icons type="compose" size="16" color="#4CAF50"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrOnboardingRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type {
  ISysHrOnboardingRequestBillView,
  ISysHrOnboardingRequestBillQuery,
} from "./api/interface";

// 创建API实例
const api = SysHrOnboardingRequestBillApi();
const commonApiInstance = commonApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段（按优先级排列）
const visibleFields = [
  {
    key: "Name",
    label: "姓名",
    formatter: (value: any) => value || "",
  },
  {
    key: "StaffNo",
    label: "工号",
    formatter: (value: any) => value || "",
  },
  {
    key: "Phone",
    label: "手机号",
    formatter: (value: any) => value || "",
  },
  {
    key: "Gender",
    label: "性别",
    formatter: (value: any) => value || "",
  },
  {
    key: "IdCardNo",
    label: "身份证号",
    formatter: (value: any) => value || "",
  },
  {
    key: "HireDate",
    label: "入职日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "EmploymentType",
    label: "用工形式",
    formatter: (value: any) => value || "",
  },
  {
    key: "ContractType",
    label: "劳动合同类型",
    formatter: (value: any) => value || "",
  },
  {
    key: "GroupName",
    label: "所属部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "OrgName",
    label: "人事组织",
    formatter: (value: any) => value || "",
  },
  {
    key: "JobPositionName",
    label: "工作岗位",
    formatter: (value: any) => value || "",
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "BillCode",
    label: "单据编号",
    formatter: (value: any) => value || "",
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => {
      if (value === 0 || value === "草稿") return "草稿";
      if (value === 1 || value === "正文") return "正文";
      return value || "";
    },
  },
  {
    key: "WorkflowStatus",
    label: "工作流状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "name",
    label: "员工姓名",
    placeholder: "请输入员工姓名",
  },
  {
    key: "staffNo",
    label: "员工工号",
    placeholder: "请输入员工工号",
  },
  {
    key: "phone",
    label: "手机号",
    placeholder: "请输入手机号",
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "gender",
    label: "性别",
    type: "selector",
    placeholder: "请选择性别",
    options: ["男", "女"],
  },
  {
    key: "idCardNo",
    label: "身份证号",
    placeholder: "请输入身份证号",
  },
  {
    key: "employmentType",
    label: "用工形式",
    type: "selector",
    placeholder: "请选择用工形式",
    options: ["全职", "兼职", "实习", "外包"],
  },
  {
    key: "contractType",
    label: "劳动合同类型",
    type: "selector",
    placeholder: "请选择劳动合同类型",
    options: ["固定期限", "无固定期限", "项目合同"],
  },
  {
    key: "groupId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "workflowStatus",
    label: "工作流状态",
    type: "selector",
    placeholder: "请选择工作流状态",
    options: ["待提交", "提交中", "审核中", "已完成", "已取消"],
  },
  {
    key: "approvalTime",
    label: "审批时间",
    type: "daterange",
    placeholder: "请选择审批时间范围",
  },
];

// 定义操作按钮
const actions = [
  {
    key: "delete",
    label: "删除",
    icon: "trash",
    color: "#FF5252",
    class: "delete-btn",
  },
  {
    key: "edit",
    label: "编辑",
    icon: "compose",
    color: "#4CAF50",
    class: "edit-btn",
  },
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 入职申请列表数据
const onboardingList = ref<ISysHrOnboardingRequestBillView[]>([]);

// 部门数据缓存（用于名称和ID的转换）
const departmentDataCache = ref<any[]>([]);

// 删除入职申请
const handleDelete = async (item: ISysHrOnboardingRequestBillView) => {
  try {
    // 调用删除API，传入ID数组
    await api.delete([item.ID!]);

    // 显示成功提示
    uni.showToast({
      title: "删除成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    // 显示错误提示
    uni.showToast({
      title: "删除失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  }
};

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysHrOnboardingRequestBillQuery = {
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    };

    // 根据筛选参数构建查询对象
    if (filterParams.name) {
      queryParams.Name = filterParams.name;
    }
    if (filterParams.staffNo) {
      queryParams.StaffNo = filterParams.staffNo;
    }
    if (filterParams.phone) {
      queryParams.Phone = filterParams.phone;
    }
    if (filterParams.idCardNo) {
      queryParams.IdCardNo = filterParams.idCardNo;
    }
    if (filterParams.gender) {
      // 直接使用性别字符串
      queryParams.Gender = filterParams.gender;
    }
    if (filterParams.employmentType) {
      // 用工形式现在直接使用文字
      queryParams.EmploymentType = filterParams.employmentType;
    }
    if (filterParams.contractType) {
      // 劳动合同类型现在直接使用文字
      queryParams.ContractType = filterParams.contractType;
    }
    if (filterParams.groupId) {
      // XenDepartmentPicker组件直接返回部门ID
      queryParams.GroupId = filterParams.groupId;
    }
    // 处理审批时间范围：确保结束日期包含当天的所有时间
    const approvalTimeRange = processDateRangeField(
      filterParams,
      "approvalTime",
    );
    if (approvalTimeRange) {
      queryParams.ApprovalTime = approvalTimeRange;
    }
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.billStatus) {
      queryParams.BillStatus = filterParams.billStatus === "草稿" ? 0 : 1;
    }
    if (filterParams.workflowStatus) {
      // 直接传递文字，不转换为数字
      queryParams.WorkflowStatus = filterParams.workflowStatus;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      onboardingList.value = response.Data;
    } else {
      onboardingList.value = [];
    }
  } catch (error) {
    onboardingList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysHrOnboardingRequestBillView[]) => {
  onboardingList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (onboardingList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    });

    if (response && response.Data) {
      onboardingList.value = response.Data;
    } else {
      onboardingList.value = [];
    }
  } catch (error) {
    onboardingList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取入职申请信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载部门数据和组织数据
const loadDepartmentData = async () => {
  try {
    // 加载部门数据
    const departmentResponse = await commonApiInstance.GetParentsTree();
    if (departmentResponse && Array.isArray(departmentResponse)) {
      // 缓存部门数据
      departmentDataCache.value = departmentResponse;

      // 找到部门筛选字段并更新其部门数据
      const departmentField = filterFields.find(
        (field) => field.key === "groupId",
      );
      if (departmentField) {
        departmentField.departmentData = departmentResponse;
      }
    }
  } catch (error) {
    console.error("加载部门/组织数据失败:", error);
  }
};

// 页面加载
onMounted(async () => {
  await loadDepartmentData();
  fetchData();
});
</script>
